﻿using AutoMapper;
using IntelligentAgriculture.Contracts.Dto.Input;
using IntelligentAgriculture.Contracts.Dto.Output;
using IntelligentAgriculture.Contracts.Interface;
using IntelligentAgriculture.Domain;
using IntelligentAgriculture.Domain.Entity;
using IntelligentAgriculture.Domain.Interface;
using IntelligentAgriculture.Domain.Interface.IColumnManagement;
using IntelligentAgriculture.Domain.Interface.Iridgepletype;
using IntelligentAgriculture.Domain.Interface.SheepFileModelInterface;
using Microsoft.Extensions.Logging;
using SixLabors.Fonts.Tables.AdvancedTypographic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace IntelligentAgriculture.Services
{
	/// <summary>
	/// 后裔转种
	/// </summary>
	public class DescendantTransferService:IDescendantTransferService
	{
		/// <summary>
		/// 后裔转种
		/// </summary>
		private readonly IDescendantTransferRepository _descendantTransferRepository;
		private readonly ILogger<LambweaninginfoService> _logger;
		private readonly AgricultureDbContext _db;
		private readonly IMapper _mapper;
		/// <summary>
		/// 养只档案
		/// </summary>
		private readonly ISheepFileModelRepository _shepFileModelRepository;
		/// <summary>
		/// 栋舍
		/// </summary>
		private readonly IridegRepository _iridegRepository;
		/// <summary>
		/// 栏位
		/// </summary>
		private readonly IColumnManRepository _columnManRepository;
		/// <summary>
		/// 转舍记录
		/// </summary>
		private readonly IPurchaseFormModelRepository _purchaseFormModelRepository;
		/// <summary>
		/// 羔羊断奶
		/// </summary>
		private readonly ILambweaninginfoRepository _lambweaninginfoRepository;
		/// <summary>
		/// 构造函数
		/// </summary>
		/// <param name="descendantTransferRepository"></param>

		public DescendantTransferService(IDescendantTransferRepository descendantTransferRepository, ILogger<LambweaninginfoService> logger, AgricultureDbContext db, IMapper mapper, ISheepFileModelRepository shepFileModelRepository, IridegRepository iridegRepository, IColumnManRepository columnManRepository, IPurchaseFormModelRepository purchaseFormModelRepository, ILambweaninginfoRepository lambweaninginfoRepository)
		{
			_descendantTransferRepository = descendantTransferRepository;
			_logger = logger;
			_db = db;
			_mapper = mapper;
			_shepFileModelRepository = shepFileModelRepository;
			_iridegRepository = iridegRepository;
			_columnManRepository = columnManRepository;
			_purchaseFormModelRepository = purchaseFormModelRepository;
			_lambweaninginfoRepository = lambweaninginfoRepository;

		}
		/// <summary>
		/// 获取后裔转种列表
		/// </summary>
		/// <returns></returns>
		public async Task<PageOutput<DescendanttransferOutPut>> GetDescendanttransfers(DescendantTransferInPut input)
		{
			try
			{
				var descend = await _descendantTransferRepository.GetDescendanttransfers();
				//栋舍
				var rigin =  _iridegRepository.Showinfo();
				//栏位
				var colum =  _columnManRepository.GetShow();
				var descendList = from a in descend
								  join b in rigin on a.CurrentBuilding equals b.RidgepoleId
								  join c in colum on a.CurrentField equals c.ColumnManagementId
								  select new DescendanttransferOutPut()
								  {
									  CreateName = a.CreateName,
									  CreateTime = a.CreateTime,
									  CurrentBuilding = a.CurrentBuilding,
									  //当前栋舍
									  CurrentBuildingName = rigin.FirstOrDefault(c => c.RidgepoleId == a.CurrentBuilding).RidgepoleName,
									  CurrentField = a.CurrentField,
									  //当前栏位
									  CurrentFieName = colum.FirstOrDefault(c => c.ColumnManagementId == a.CurrentField).ColumnName,
									  DescendantDate = a.DescendantDate,
									  DescendantId = a.DescendantId,
									  DescendantSex = a.DescendantSex,
									  EarTag = a.EarTag,
									  IsDel = a.IsDel,
									  ToBuildingManageId = a.ToBuildingManageId,
									  //转出栋舍
									  ToBuildingManageName = rigin.FirstOrDefault(c => c.RidgepoleId == a.ToBuildingManageId).RidgepoleName,
									  ToColumMangementId = a.ToColumMangementId,
									  //转出栏位
									  ToColumMangementName = colum.FirstOrDefault(c => c.ColumnManagementId == a.ToColumMangementId).ColumnName,
									  UpdateName = a.UpdateName,
									  UpdateTime = a.UpdateTime,
								  };
				if(!string.IsNullOrEmpty(input.startDate))
				{
					descendList = descendList.Where(c => c.DescendantDate >= DateTime.Parse(input.startDate));
				}
				if (!string.IsNullOrEmpty(input.endDate))
				{
					descendList = descendList.Where(c => c.DescendantDate < DateTime.Parse(input.endDate).AddDays(1));
				}
				if(!string.IsNullOrEmpty(input.eatTag))
				{
					descendList = descendList.Where(c => c.EarTag.Contains(input.eatTag));
				}
				var result = new PageOutput<DescendanttransferOutPut>
				{
					PageSize = input.pageSize,
					TotalCount = descendList.Count(),
				};
				result.Data=descendList.OrderByDescending(c=>c.CreateTime).Skip((input.pageIndex - 1) * input.pageSize).Take(input.pageSize).ToList();
				return result;
			}
			catch (Exception ex)
			{
				_logger.LogError("获取后裔转种列表异常" + ex.Message);
				throw;
			}
		}
		/// <summary>
		/// 删除
		/// </summary>
		/// <param name="idList"></param>
		/// <returns></returns>
		public async Task<int> DelDescendanttransfer(params string[] eartag)
		{
			try
			{
				string randomLoginName = GetRandomLoginName(); // 获取随机登录名

				// 调用仓储删除对应登录名和耳标的记录
				return await _descendantTransferRepository.DelDescendanttransfer(randomLoginName, eartag);

				
			}
			catch (Exception ex)
			{
				_logger.LogError("处理后代转移时发生异常: " + ex.Message);
				throw; // 继续抛出异常以便上层处理
			}
		}

		private string GetRandomLoginName()
		{
			string[] loginNames = { "孟盘龙", "刘永刚", "赵思彤", "赵秋实", "牛骞若", "于晋哲" };
			Random random = new Random();
			int randomIndex = random.Next(0, loginNames.Length);
			return loginNames[randomIndex];
		}
			/// <summary>
			/// 添加后裔转种
			/// </summary>
			/// <param name="entity"></param>
			/// <returns></returns>
		public async Task<int> AddDelDescendanttransfer(List<Descendanttransfer> entity)
		{
			using(var tran = _db.Database.BeginTransaction())
			{
				try
				{
					//共有属性
					entity.ForEach(c =>
					{
						c.CreateName = "孟盘龙";
						c.CreateTime = DateTime.Now;
						c.IsDel = false;
					});
					await _descendantTransferRepository.AddDelDescendanttransfer(entity);
					//羊只档案接口
					var sheepfile = await _shepFileModelRepository.GetSheepfilemodels();
					//循环添加羊只转舍
					var sheeprescissions = entity.Select(c => new Sheeprescission()
					{
						SheepRescissionDate = DateTime.Now,
						EarTag = c.EarTag,
						RoundType = 12,
						OutBuildingManageId = c.CurrentBuilding,
						OutColumMangementId = c.CurrentField,
						ToBuildingManageId = c.ToBuildingManageId,
						ToColumMangementId = c.ToColumMangementId,
						SheepType = 3,
						Variety = sheepfile.FirstOrDefault(c => c.EarTag == c.EarTag)?.Variety,
						SheepRescissionSex = c.DescendantSex,
						CreateName = "孟盘龙",
						CreateTime = DateTime.Now,
						Isdel = false,
						UpdateName = "孟盘龙",
						UpdateTime = DateTime.Now,
						DocumentNumber=YitIdHelper.NextId().ToString(),
				}).ToList();
					await _purchaseFormModelRepository.AddPurchaseFormModel(sheeprescissions);
					//获取耳号
					var descentran = entity.Select(c => c.EarTag).ToList();
					//通过耳号查询档案获取档案
					var ear = sheepfile.Where(c => descentran.Contains(c.EarTag)).ToList();
					//更新档案表
					ear.ForEach(c =>
					{
						var sex = entity.FirstOrDefault(c => c.EarTag == c.EarTag).DescendantSex;
						if (sex == true)
						{
							c.Growthstage = 3;
							c.SheepType = 1;
						}
						else
						{
							c.Growthstage = 4;
							c.SheepType = 2;
						}
						c.ColumnId = entity.FirstOrDefault(d => d.EarTag == c.EarTag).ToColumMangementId;
						c.BuildingId = entity.FirstOrDefault(d => d.EarTag == c.EarTag).ToBuildingManageId;
					});
					 await _shepFileModelRepository.UpdateListSheepFileModel(ear);
					tran.Commit();
					//获取羔羊断奶
					var lamb= await _lambweaninginfoRepository.GetLambweaninginfos();
					//通过耳号查询羔羊断奶获取羔羊断奶
					var lamear = lamb.Where(c => descentran.Contains(c.EarTag)).ToList();
					lamear.ForEach(c =>
					{
						c.EarTag= entity.FirstOrDefault(d => d.EarTag == c.EarTag).EarTag;
						c.IsDel = true;
					});
					 await _lambweaninginfoRepository.UpdateListLambweaninginfo(lamear);
					tran.Commit();
					return 1;
				}
				catch (Exception ex)
				{
					_logger.LogError("添加后裔转种异常" + ex.Message);
					throw;
				}

			}
			
		}
		/// <summary>
		/// 反填后裔转种
		/// </summary>
		/// <param name="eartag"></param>
		/// <returns></returns>
		public async Task<Descendanttransfer> DetaileDescendanttransfer(string eartag)
		{
			try
			{
				return await _descendantTransferRepository.DetaileDescendanttransfer(eartag);
			}
			catch (Exception ex)
			{
				_logger.LogError("反填后裔转种异常" + ex.Message);
				throw;
			}
			
		}
		/// <summary>
		/// 修改后裔转种
		/// </summary>
		/// <param name="entity"></param>
		/// <returns></returns>
		public async Task<int> UpdateDescendanttransfer(Descendanttransfer entity)
		{
			try
			{
				await _descendantTransferRepository.UpdateDescendanttransfer(entity);
				var descend = await _shepFileModelRepository.GetSheepfilemodels();
				var list = descend.FirstOrDefault(c => c.EarTag == entity.EarTag);
				list.ColumnId = entity.ToColumMangementId;
				list.BuildingId = entity.ToBuildingManageId;
				if(entity.DescendantSex==true)
				{
					list.Growthstage = 3;
					list.SheepType = 1;
				}
                else
                {
					list.Growthstage = 4;
					list.SheepType = 2;
				}
                return await _shepFileModelRepository.UpdaSheepFileModel(list);
			}
			catch (Exception ex)
			{
				_logger.LogError("修改后裔转种异常" + ex.Message);
				throw;
			}
		}
	}
}
